package cn.xiaoyu.su.service.impl;

import cn.xiaoyu.su.component.SmsComponent;
import cn.xiaoyu.su.config.SmsConfig;
import cn.xiaoyu.su.constant.CacheKey;
import cn.xiaoyu.su.constant.TimeConstant;
import cn.xiaoyu.su.enums.BizCodeEnum;
import cn.xiaoyu.su.enums.SendCodeEnum;
import cn.xiaoyu.su.service.NotifyService;
import cn.xiaoyu.su.util.CommonUtil;
import cn.xiaoyu.su.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author sufs
 * @date 2022/10/27 14:55
 */
@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    SmsComponent smsComponent;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param sendCodeEnum
     * @param to
     * @return
     */
    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey = String.format(CacheKey.SEND_CODE_KEY,sendCodeEnum.name(),to);
        String cacheCode = redisTemplate.opsForValue().get(cacheKey);

        long now = CommonUtil.getCurrentTimestamp();

        if (StringUtils.isNotBlank(cacheCode)) {
            long before = Long.parseLong(cacheCode.split("_")[1]);

            if (now - before < TimeConstant.SEND_CODE_LIMIT) {
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        String sendCode = CommonUtil.getRandomCode(6);

        redisTemplate.opsForValue().set(cacheKey,sendCode+"_"+now,TimeConstant.SEND_CODE_EXPIRED_TIME, TimeUnit.MILLISECONDS);

        smsComponent.sendCode(to, smsConfig.getTemplateId(),sendCode);

        return JsonData.buildSuccess(sendCode);
    }
}
